package model

import (
	"blog/errmsg"
	"encoding/base64"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/scrypt"
)

type User struct {
	gorm.Model
	Token string `gorm:"-" json:"token"`
	Username string `gorm:"type:varchar(20);not null" json:"username" validate:"required,min=4,max=12" label:"用户名"`
	Password string `gorm:"type:varchar(32);not null" json:"password" validate:"required,min=6" label:"密码"`
	Role int   `gorm:"type:int;default:2" json:"role" validate:"required,gte=2" label:"角色码"` //1管理员 2普通用户
}

func UserIsExists(username string)(code int,msg string){
	var user User
	if err := db.Select("id").Where("username = ?",username).First(&user).Error;err!=nil && err!=gorm.ErrRecordNotFound{
		return errmsg.FAIL,err.Error()
	}
	if user.ID > 0{
		return errmsg.ERROR_USER_USERNAME_HAVED,""
	}
	return errmsg.SUCCESS,""
}

func (this *User)Login()(User,int){
	var user User
	fdb := db.Where("username = ? and password = ?",this.Username,ScryptPass(this.Password)).First(&user)
	if fdb.Error!=nil{
		return User{},errmsg.ERROR_USER_VERIFY_WRONG
	}
	return user,errmsg.SUCCESS
}

func CreateUser(this *User)(code int,msg string){
	code,msg = UserIsExists(this.Username)
	this.Password = ScryptPass(this.Password)
	if code == errmsg.SUCCESS {
		if err := db.Create(this).Error;err!=nil{
			return errmsg.FAIL,"注册失败 " + err.Error()
		}
		return errmsg.SUCCESS,""
	}
	return
}
func GetUser(id int)(code int,msg string,user User){
	var u  User
	if err := db.Where("id = ? ",id).First(&u).Error;err!=nil{
		return errmsg.FAIL,err.Error(),User{}
	}
	return errmsg.SUCCESS,"",u
}
func GetUsers(page,pagesize int)(code int ,msg string, users []User,tl int){
	var total int
	if err:=db.Limit(pagesize).Offset((page-1)*pagesize).Find(&users).Count(&total).Error;err!=nil && err!=gorm.ErrRecordNotFound{
		return errmsg.FAIL,err.Error(),users,0
	}
	return errmsg.SUCCESS,"",users,total
}
func UpdateUser(user User) (code int,msg string){
	code,msg = UserIsExists(user.Username)
	if code == errmsg.SUCCESS {
		maps := make(map[string]interface{})
		maps["username"] = user.Username
		maps["role"] = user.Role
		udb := db.Model(user).Updates(maps)
		if err := udb.Error;err!=nil{
			return errmsg.FAIL,err.Error()
		}
		if udb.RowsAffected == 0{
			return errmsg.FAIL,"更新失败,该条数据不存在！"
		}
		return errmsg.SUCCESS,""
	}
	return code,msg
}
func DeleteUser(user *User) (code int,msg string){
	ddb := db.Delete(user)
	if err := ddb.Error;err!=nil{
		return errmsg.FAIL,err.Error()
	}
	if ddb.RowsAffected == 0{
		return errmsg.FAIL,"删除失败，该条数据不存在！"
	}
	return errmsg.SUCCESS,""
}
//Hooks函数
//func (this *User)BeforeSave(){
//	this.Password = ScryptPass(this.Password)
//	fmt.Println("--BeforeSave--")
//}
//func (this *User)BeforeCreate(){
//	 fmt.Println("--BeforeCreate--")
//}
//func (this *User)AfterCreate(){
//	fmt.Println("--AfterCreate--")
//}
//func (this *User)AfterSave(){
//	fmt.Println("--AfterSave--")
//}
//密码加密 scrypt方案
func ScryptPass(password string)string{
	salt := []byte{61,12,64,45,15,46,76,87}//加盐
	bt,err := scrypt.Key([]byte(password),salt,1<<15, 8, 1, 20)
	if err!=nil{
		panic(err)
	}
	return base64.StdEncoding.EncodeToString(bt)
}
